import {VNode, VNodeChild} from "vue";
import {RouteLocationNamedRaw, RouteLocationNormalizedLoaded, RouteLocationPathRaw, Router} from "vue-router";

import i18n from '@/lang/index';

export function translateRouteTitleI18n(title: any) {
    // 判断是否存在国际化配置，如果没有原生返回
    const hasKey = i18n.global.te('route.' + title);
    if (hasKey) {
        const translatedTitle = i18n.global.t('route.' + title);
        return translatedTitle;
    }
    return title;
}

/**
 * @param {string} path
 * @returns {Boolean}
 */
export function isExternal(path: string) {
    const isExternal = /^(https?:|http?:|mailto:|tel:)/.test(path);
    return isExternal;
}

/** 菜单数据转换成UI的菜单配置 */
export function menuToMenuOption(menu: any, deep: any) {
    const menuOption: any = {
        key: menu.id!,
        label: menu.name,
        // icon: renderIcon(menu.icon), // TODO: renderIcon
        menu: menu,
    };
    if (deep && menu.children && menu.children.length > 0) {
        menuOption.children = [];
        for (let child of menu.children) {
            menuOption.children.push(menuToMenuOption(child, true));
        }
    }
    return menuOption;
}

/** 返回一级菜单 */
export function getTopMenuOptions(menus: any[], deep: boolean = false): any[] {
    const topMenu: any[] = [];
    for (let menu of menus) {
        topMenu.push(menuToMenuOption(menu, deep));
    }
    return topMenu;
}

/** 返回一级菜单 */
export function getTopMenuOption(topMenu: any): any {
    return menuToMenuOption(topMenu, true);
}

/** 获取当前Layout所对应的菜单 */
export function getMenus(route: RouteLocationNormalizedLoaded): any[] {
    const matched = route.matched;
    if (matched?.length < 1) return [];
    const {meta} = matched[0];
    return (meta as any)?.menus ?? [];
}

/** 获取当前Layout选中的一级菜单 */
export function getSelectedTopMenu(route: RouteLocationNormalizedLoaded): any | undefined {
    const matched: any = route.matched;
    if (matched?.length < 2) return;
    const {meta} = matched[1];
    return meta?.menu;
}

/** 获取当前Layout选中的最后一级菜单 */
export function getSelectedSideMenu(route: RouteLocationNormalizedLoaded): any | undefined {
    const matched: any = route.matched;
    if (matched.length <= 0) return;
    const {meta} = matched[matched.length - 1];
    return meta?.menu;
}

/** 根据菜单跳转路由 */
export async function routerPush(router: Router, menu: any, options: RouteLocationPathRaw | RouteLocationNamedRaw = {}) {
    return router.push({
        ...options,
        name: menu.id,
    });
}
